package fb.vis.login;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




/**
 * Servlet implementation class AfterLogin
 */
@WebServlet(name = "AfterLogin", urlPatterns = {"/AfterLogin"})
public class AfterLogin extends HttpServlet {
    private static final long serialVersionUID = 2L;


        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        @Override
        protected void doGet(HttpServletRequest request,
                        HttpServletResponse response) throws ServletException, IOException {
                doPost(request, response);
        }


        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        @Override
        protected void doPost(HttpServletRequest request,
                        HttpServletResponse response) throws ServletException, IOException {
            System.out.println("post");
            String token = getToken(request, response);
            request.getSession().setAttribute("token", token);
            response.sendRedirect(request.getContextPath()+"/HomePage");
        }


        private String getToken(HttpServletRequest request,
                        HttpServletResponse response) throws ServletException, IOException {
                String urlStr = "https://graph.facebook.com/oauth/access_token?client_id="
                                + LoginManager.appId
                                + "&redirect_uri=http://localhost:8080/FBVis/AfterLogin&client_secret="
                                + LoginManager.appSecret + "&code="
                                + request.getParameter("code");
                //test. vypis
                System.out.println(urlStr);
                //response.sendRedirect(urlStr);
                URL url = new URL(urlStr);
                //get token from url
                BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
                String tokenLine = br.readLine();
                String[] tokens = tokenLine.split("&");
                System.out.println(tokens[0]);
                System.out.println(tokens[1]);
                
                String[] oAuthTokenS = tokens[0].split("=");
                String token = oAuthTokenS[1];
                //TOKEN!!
                System.out.println(token);
                
                return token;
        }


        
        
    
}